<template>
	<div>
		<!-- 要截图的元素 -->
		<div ref="captureRef" class="capture-area">
			<h1>Hello html2canvas!</h1>
			<p>This content will be captured</p>
		</div>

		<!-- 触发按钮 -->
		<button @click="capture">生成图片</button>

		<!-- 预览区域 -->
		<img v-if="imageUrl" :src="imageUrl" alt="Captured Image" />
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import html2canvas from 'html2canvas';

// 元素引用
const captureRef = ref<HTMLElement | null>(null);
const imageUrl = ref<string>('');

const capture = async () => {
	if (!captureRef.value) return;

	try {
		// 配置选项（可选）
		const options: html2canvas.Options = {
			scale: 1, // 缩放比例
			useCORS: true, // 允许跨域图片
			logging: true, // 调试日志
			backgroundColor: 'rgba(0, 0, 0, 0)',
		};

		// 生成 canvas
		const canvas = await html2canvas(captureRef.value, options);

		// 转换为图片 URL
		const url = canvas.toDataURL('image/png');
		imageUrl.value = url;

		// 自动下载图片
		const link = document.createElement('a');
		link.download = 'capture.png';
		link.href = url;
		link.click();
	} catch (error) {
		console.error('截图失败:', error);
	}
};
</script>

<style>
.capture-area {
	padding: 20px;
	background: #f0f0f0;
	border: 2px dashed #ccc;
}
</style>
